package 剑指offer;

/**
 * @description: 给一个01矩阵，1代表是陆地，0代表海洋， 如果两个1相邻，那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
 * 岛屿: 相邻陆地可以组成一个岛屿（相邻:上下左右） 判断岛屿个数。
 * @author: ywk
 * @date: 2021-02-19
 */
public class 岛屿数量 {
    /**
     * 判断岛屿数量
     *
     * @param grid char字符型二维数组
     * @return int整型
     */
      static boolean[][] visited;

    static int count = 0;

    public static int solve(char[][] grid) {
        // write code here
        visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                isValid(grid, i, j);
            }
        }
        return count;
    }
    public static int isValid(char[][] grid, int x, int y) {
        if (x >= grid.length || y >= grid[0].length || x < 0 || y < 0) {
            return 0;
        }
        if (grid[x][y] == '0') {
            return 0;
        }
        if (visited[x][y]) {
            return 1;
        }

        visited[x][y] = true;
        int solve = isValid(grid, x - 1, y) + isValid(grid, x + 1, y) + isValid(grid, x, y - 1) + isValid(grid, x, y + 1);
        grid[x][y] = '0';
        if (solve == 0) {
            count++;
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
//        System.out.println(solve(toCharArr(new int[][]{{1, 1, 0, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}})));
        System.out.println(solve(toCharArr(new int[][]{{1, 1}, {1, 1}})));

        System.out.println(count);
    }

  public   static char[][] toCharArr(int[][] arr) {
        char[][] chars = new char[arr.length][arr[0].length];
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                chars[i][j] = (char) (arr[i][j] + '0');
            }
        }
        return chars;
    }

}
